<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = '文章列表';
        //²éÑ¯ÎÄÕÂÊý¾Ý
        $data = DB::table('bro_article') ->where(function($query) use ($request){
            $query -> where('title','like','%'.$request -> input('keywords').'%');
        }) -> paginate($request -> input('num',10));

        //会话控制
        $staff = $request->session()->get('staff');

        //ÏòÓÃ»§ÁÐ±í·¢ËÍÊý¾Ý
        return view('admin.article.index',['title' => $title,'data' => $data,'request' => $request -> all(),'staff' => $staff]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        //ÎÄÕÂÌí¼ÓÒ³Ãæ
        $title = '文章添加';

        $staff = $request->session()->get('staff');

        return view('admin.article.add',['title' => $title,'staff'=>$staff]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //Ö´ÐÐÎÄÕÂÌí¼Ó·½·¨
        // dd($request -> all());
        // È¥³ýÒþ²Ø_token
        $data = $request -> except('_token');

        $staff = $request->session()->get('staff');

         //¼ì²âÌí¼ÓÒ³ÃæµÄÊý¾Ý²¢Ö´ÐÐÏìÓ¦
        $this -> validate($request,[
            'title' => 'required',
            'content' => 'required',
            'pic' => 'required',

        ],[

            'title.required' => '文章标题不能为空',
            'content.required' => '文章内容不能为空',
            'pic.required' => '文章图片不能为空',
            
        ]);

        //ÅÐ¶ÏÉÏ´«ÎÄ¼þÊÇ·ñÉÏ´«ºÍÊÇ·ñÓÐÐ§
        if($request -> hasFile('pic'))
        {
            if($request -> file('pic') -> isValid())
            {
                $arr= array('jpg','png','gif');
                //»ñÈ¡ÎÄ¼þµÄºó×ºÃû
                $suffix = $request -> file('pic') -> getClientOriginalExtension();
                if(in_array($suffix,$arr))
                {
                  //Æ´½ÓÎÄ¼þÃû
                  $fileName = time().rand(100000,999999).'.'.$suffix;

                  $path = date('Ymd');
                  $data['pic'] = '/uploads/'.$path.'/'.$fileName;
                  
                  $request -> file('pic') ->move('./uploads/'.$path,$fileName);
                }else{
                  return back() -> with('error','上传文件不合法');
                }
                
            }
          $data['atime'] = time();//ÎÄÕÂ·¢²¼Ê±¼ä

          $data['uptime'] = time();//ÎÄÕÂ¸üÐÂÊ±¼ä

          //Ö´ÐÐÌí¼Ó
          $res = DB::table('bro_article') -> insert($data);

        }

        //ÅÐ¶ÏÌí¼ÓÊÇ·ñ³É¹¦
        if($res)
        {
            return redirect('/admin/article') -> with('success','文章添加成功');
        }else{
            return back() -> with('error','文章添加失败');
        }
        
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        //ÎÄÕÂ±à¼­Ò³Ãæ
        $title = '文章编辑';

        //»ñÈ¡Òª±à¼­µÄÎÄÕÂÊý¾Ý
        $data = DB::table('bro_article') -> where('id',$id) -> first();
        // dd($data);
        $staff = $request->session()->get('staff');

        //Ìø×ª±à¼­Ò³Ãæ²¢·¢ËÍÊý¾Ý
        return view('admin.article.edit',['title' => $title,'data'=>$data,'staff' => $staff]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //Ö´ÐÐÐÞ¸Ä
        //
        $this -> validate($request,[
            'title' => 'required',
            'content' => 'required',
           

        ],[

            'title.required' => '文章标题不能为空',
            'content.required' => '文章内容不能为空',
           
            
        ]);
        //È¥³ýÎÞÓÃµÄ×Ö¶Î
        $data = $request -> except('_token','_method','oldpic');

        //»ñÈ¡Ô­À´µÄÎÄÕÂÍ¼Æ¬
        $oldpic ='.'. $request -> input('oldpic');

        // dd($oldpic);
        // 
        //ÅÐ¶ÏÊÇ·ñÉÏ´«µÄÍ¼Æ¬,ÉÏ´«µÄÍ¼Æ¬ÊÇ·ñÓÐÐ§
        if($request -> hasFile('pic'))
        {
            if($request -> file('pic') ->isValid())
            {   
                $arr= array('jpg','gif','png');
                //»ñÈ¡ÎÄ¼þµÄºó×ºÃû
                 $suffix = $request -> file('pic') -> getClientOriginalExtension();
                if(in_array($suffix,$arr))
                {
                  ///Æ´½ÓÎÄ¼þÃû
                  $fileName = time().rand(100000,999999).'.'.$suffix;

                  $path = date('Ymd');
                  
                  $data['pic'] = '/uploads/'.$path.'/'.$fileName;
                  //ÒÆ¶¯ÎÄÕÂÍ¼Æ¬
                  $request -> file('pic') ->move('./uploads/'.$path,$fileName);

                  $oldpath = '.'.$request -> input('oldpic');
                  // dd($oldpath);

                  if(file_exists($oldpic))
                  {
                      
                        unlink($oldpath);
                     
                  }
                }else{
                  return back() -> with('error','上传文件不合法');
                }
                
            }
          //文章更新时间
        
          $data['uptime'] = time();
          // dd($data);
          //Ö´ÐÐÐÞ¸Ä
          $res = DB::table('bro_article') -> where('id',$id) ->update($data);
        }
        
        //ÅÐ¶ÏÊÇ·ñÐÞ¸Ä³É¹¦
         //ÅÐ¶ÏÌí¼ÓÊÇ·ñ³É¹¦
        if($res)
        {
            return redirect('/admin/article') -> with('success','文章更新成功');
        }else{
            return back() -> with('error','文章更新失败');
        }


    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //删除文章图片
        $pic = DB::table('bro_article')-> where('id',$id) -> first() -> pic;
        $oldpath = '.'.$pic;
        // dd($oldpath);
        if(file_exists($oldpath))
        {
            
              unlink($oldpath);
        }

        //文章删除
        $res = DB::table('bro_article') -> where('id',$id) ->delete();

        //判断文章删除是否成功
        if($res)
        {
            return redirect('/admin/article') -> with('success','文章删除成功');
        }else{
            return back() -> with('error','文章删除失败');
        }

    }
}
